package com.atguigu.tingshu.album.task;

import cn.hutool.core.collection.CollUtil;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.service.AuditService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;


@Slf4j
@Component
public class ReviewTask {

    @Autowired
    private TrackInfoMapper trackInfoMapper;

    @Autowired
    private AuditService auditService;

    /**
     * 每5秒检查一次审核结果
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void checkReviewResultTask() {
        log.info("开始检查审核任务");
        //1.查询审核状态为"审核中"声音列表
        List<TrackInfo> trackInfoList = trackInfoMapper.selectList(
                new LambdaQueryWrapper<TrackInfo>()
                        .eq(TrackInfo::getStatus, SystemConstant.TRACK_STATUS_REVIEWING)
                        .select(TrackInfo::getId, TrackInfo::getReviewTaskId)
                        .last("limit 100")
        );
        //2.遍历列表，查询审核结果
        if (CollUtil.isNotEmpty(trackInfoList)) {
            for (TrackInfo trackInfo : trackInfoList) {
                String suggestion = auditService.getReviewResult(trackInfo.getReviewTaskId());
                if (StringUtils.isNotBlank(suggestion)) {
                    //3.根据审核任务结果更新声音审核状态
                    if ("pass".equals(suggestion)) {
                        trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);
                    } else if ("block".equals(suggestion)) {
                        trackInfo.setStatus(SystemConstant.TRACK_STATUS_NO_PASS);
                    } else if ("review".equals(suggestion)) {
                        trackInfo.setStatus(SystemConstant.TRACK_STATUS_ARTIFICIAL);
                    }
                    trackInfoMapper.updateById(trackInfo);
                }
            }
        }
    }

}
